package org.example.me.service;

import lombok.extern.slf4j.Slf4j;
import org.example.me.entity.ExcelLog;
import org.example.me.enums.ExcelTypeEnum;
import org.example.me.handler.ExcelExportFactory;
import org.example.me.handler.template.ExcelExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

/**
 * Excel导出服务类
 * 负责执行实际的Excel导出操作，包括状态管理、异常处理等
 */
@Slf4j
@Service
public class ExcelExportService {

    @Autowired
    private ExcelExportFactory excelExportFactory;

    /**
     * 根据ID导出Excel
     *
     * @param id Excel记录ID
     */
    public void export(String id) {
        export(getExcelLog(id));
    }

    /**
     * 根据ID获取Excel日志信息
     *
     * @param id Excel记录ID
     * @return Excel日志对象
     */
    public ExcelLog getExcelLog(String id) {
        // 获取ExcelLog
        return null;
    }

    /**
     * 执行Excel导出操作
     * 核心导出方法，根据Excel类型选择对应的处理器执行导出
     * 同时记录导出过程的运行时间和状态
     *
     * @param excelLog Excel日志信息
     */
    public void export(ExcelLog excelLog) {
        String type = excelLog.getType();
        ExcelTypeEnum excelType = ExcelTypeEnum.getByCode(type);
        if (excelType == null) {
            return;
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ExcelExport excelExport = excelExportFactory.getExporter(excelType);
        if (excelExport != null) {
            boolean success = false;
            String msg = "成功";
            try {
                updateRuntime(excelLog);
                String url = excelExport.export(excelLog);
                excelLog.setUrl(url);
                success = true;
            } catch (Exception e) {
                log.error("Excel导出异常：{}", e.getMessage(), e);
                msg = e.getMessage();
            } finally {
                stopWatch.stop();
                excelLog.setCostTime(stopWatch.getTotalTimeMillis() / 1000);
                updateFinish(success, msg, excelLog);
            }
        }
    }

    /**
     * 更新Excel导出任务运行状态
     *
     * @param excelLog Excel日志信息
     */
    private void updateRuntime(ExcelLog excelLog) {
        excelLog.setState("RUNNING");
    }

    /**
     * 更新Excel导出任务完成状态
     *
     * @param success  是否成功
     * @param msg      消息
     * @param excelLog Excel日志信息
     */
    private void updateFinish(boolean success, String msg, ExcelLog excelLog) {
        excelLog.setState(success ? "FINISH" : "FAIL");
        excelLog.setRemark(msg);
    }
}